//
//  Table.swift
//  ptbuy
//
//  Created by MyMac on 2025/1/8.
//

import SwiftUI

struct Table: View {
    
    // 定义数据模型
    struct Item {
        var name: String
        var price: Double
        var quantity: Int
    }
    // 示例数据
       let items = [
           Item(name: "Item 1", price: 10.0, quantity: 2),
           Item(name: "Item 2", price: 20.0, quantity: 1),
           Item(name: "Item 3", price: 15.0, quantity: 5)
       ]
       
       // 计算合计
       var totalAmount: Double {
           60
       }
       
       var body: some View {
           NavigationView {
               VStack {
                   Text("产品表格")
                       .font(.largeTitle)
                       .bold()
                       .padding()
                   
                   List {
                       // 表头部分
                       Section(header: HStack {
                           Text("产品名称")
                               .fontWeight(.bold)
                           Spacer()
                           Text("单价")
                               .fontWeight(.bold)
                           Spacer()
                           Text("数量")
                               .fontWeight(.bold)
                           Spacer()
                           Text("总价")
                               .fontWeight(.bold)
                       }
                       .padding(.horizontal)) {
                           // 数据行部分
                           ForEach(items, id: \.name) { item in
                               HStack {
                                   Text(item.name)
                                   Spacer()
                                   Text(String(format: "%.2f", item.price))
                                   Spacer()
                                   Text("\(item.quantity)")
                                   Spacer()
                                   Text(String(format: "%.2f", item.price * Double(item.quantity)))
                               }
                               .padding(.vertical, 5)
                           }
                       }
                       
                       // 合计部分
                       Section {
                           HStack {
                               Text("总计")
                                   .fontWeight(.bold)
                               Spacer()
                               Text(String(format: "%.2f", totalAmount))
                                   .fontWeight(.bold)
                           }
                           .padding(.vertical, 10)
                       }
                   }
                   .listStyle(InsetGroupedListStyle()) // 修改列表样式
               }
               .navigationTitle("购物清单")
           }
       }
   }

#Preview {
    Table()
}
